﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Mengsk.ProxyDelivery.App.Extenstions;
using Mengsk.ProxyDelivery.Domain;
using Mengsk.ProxyDelivery.Service;
using Seagull.BarTender.Print;
using Mengsk.ProxyDelivery.App.Domain;
using Mengsk.ProxyDelivery.App.Device;
using System.Diagnostics;
using System.IO;
using Com.Qiniu.ShopErp.App.Device.Print;

namespace Mengsk.ProxyDelivery.App.UI.Order
{
    /// <summary>
    /// ReturnProcessUserControl.xaml 的交互逻辑
    /// </summary>
    public partial class ReturnProcessUserControl : UserControl, IPlugin
    {
        private VendorService vs = ServiceContainer.GetService<VendorService>();
        private bool myContentLoaded = false;

        public string Title
        {
            get { return "退货处理"; }
        }

        public Control UIControl
        {
            get { return this; }
        }

        public ReturnProcessUserControl()
        {
            InitializeComponent();
        }
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (myContentLoaded == true)
            {
                return;
            }
            myContentLoaded = true;
            this.cbbStates.Bind<OrderChangeState>();
            this.cbbTypes.Bind<OrderChangeType>();
        }

        private void btnQuery_Click(object sender, RoutedEventArgs e)
        {
            int id = 0;
            long orderId = 0;
            int sellerId = 0;

            int.TryParse(this.tbId.Text.Trim(), out id);
            int.TryParse(this.tbSellerId.Text.Trim(), out sellerId);
            long.TryParse(this.tbOrderId.Text.Trim(), out orderId);

            string delivery = this.tbReturnDeliveryNumber.Text.Trim();
            DateTime startTime = this.dpStartTime.Value == null ? DateTime.MinValue : this.dpStartTime.Value.Value.Date;
            DateTime endTime = this.dpEndTime.Value == null ? DateTime.MinValue : this.dpEndTime.Value.Value.Date;
            string number = this.tbNumber.Text.Trim();
            string color = this.tbColor.Text.Trim();
            string size = this.tbSize.Text.Trim();

            this.pbBar.Parameters.Clear();
            this.pbBar.Parameters.Add("id", id);
            this.pbBar.Parameters.Add("orderId", orderId);
            this.pbBar.Parameters.Add("sellerId", sellerId);
            this.pbBar.Parameters.Add("number", number);
            this.pbBar.Parameters.Add("color", color);
            this.pbBar.Parameters.Add("size", size);
            this.pbBar.Parameters.Add("timeType", this.cbbTimeType.SelectedIndex + 1);
            this.pbBar.Parameters.Add("startTime", startTime);
            this.pbBar.Parameters.Add("endTime", endTime);
            this.pbBar.Parameters.Add("state", (int)(this.cbbStates.GetSelectedEnum<OrderChangeState>()));
            this.pbBar.Parameters.Add("type", (int)(this.cbbTypes.GetSelectedEnum<OrderChangeType>()));
            this.pbBar.Parameters.Add("returnDeliveryNumber", delivery);

            this.pbBar.StartPage();
        }

        private void pbBar_PageChanging(object sender, PageBar.PageChangeEventArgs e)
        {
            var ret = ServiceContainer.GetService<OrderChangeService>().GetByAll(e.GetParameter<int>("id"), e.GetParameter<long>("orderId"), e.GetParameter<int>("sellerId"), e.GetParameter<string>("number"), e.GetParameter<string>("color"), e.GetParameter<string>("size"), e.GetParameter<int>("timeType"), e.GetParameter<DateTime>("startTime"), e.GetParameter<DateTime>("endTime"), e.GetParameter<int>("state"), e.GetParameter<int>("type"), e.GetParameter<string>("returnDeliveryNumber"), e.CurrentPage - 1, e.PageSize);
            OrderService os = ServiceContainer.GetService<OrderService>();
            List<OrderChangeViewModel> vms = new List<OrderChangeViewModel>();

            foreach (var item in ret.Datas)
            {
                OrderChangeViewModel vm = new OrderChangeViewModel();
                vm.OrderChange = item;
                vm.Order = os.GetById(item.OrderId);
                if (vm.Order != null && vm.Order.OrderGoodss != null)
                {
                    vm.OrderGoods = vm.Order.OrderGoodss.FirstOrDefault(obj => obj.Id == item.OrderGoodsId);
                }
                vms.Add(vm);
            }

            this.lstOrderChanges.ItemsSource = vms.ToArray();
            this.pbBar.Total = ret.Total;
            this.pbBar.CurrentCount = ret.Datas.Count;
        }

        private void btnViewSellerImage_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FrameworkElement fe = sender as FrameworkElement;
                if (fe == null)
                {
                    MessageBox.Show("事件源不为:FrameworkElement");
                    return;
                }
                OrderChangeViewModel vm = fe.DataContext as OrderChangeViewModel;
                OrderChangeImageViewWindow window = new OrderChangeImageViewWindow
                {
                    Image1 = vm.OrderChange.SellerImage1,
                    Image2 = vm.OrderChange.SellerImage2,
                    Image3 = vm.OrderChange.SellerImage3,
                };
                window.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnViewSystemImage_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FrameworkElement fe = sender as FrameworkElement;
                if (fe == null)
                {
                    MessageBox.Show("事件源不为:FrameworkElement");
                    return;
                }
                OrderChangeViewModel vm = fe.DataContext as OrderChangeViewModel;
                OrderChangeImageViewWindow window = new OrderChangeImageViewWindow
                {
                    Image1 = vm.OrderChange.SystemImage1,
                    Image2 = vm.OrderChange.SystemImage2,
                    Image3 = vm.OrderChange.SystemImage3
                };
                window.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnModify_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FrameworkElement fe = sender as FrameworkElement;
                if (fe == null)
                {
                    MessageBox.Show("事件源不为:FrameworkElement");
                    return;
                }
                var vm = fe.DataContext as OrderChangeViewModel;

                if (vm == null)
                {
                    MessageBox.Show("没有要修改退换货记录");
                    return;
                }

                var window = new OrderChangeDeliveryModifyWindow { OrderChange = vm };
                window.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnQueryDelivery_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Button btn = sender as Button;
                if (btn == null || btn.DataContext == null || btn.DataContext is OrderChangeViewModel == false)
                {
                    return;
                }
                var order = btn.DataContext as OrderChangeViewModel;
                Delivery.DeliveryQueryWindow window = new Delivery.DeliveryQueryWindow { DeliveryCompany = order.OrderChange.ReturnDeliveryCompany, DeliveryNumber = order.OrderChange.ReturnDeliveryNumber };
                window.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnCreateWithoutOrder_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var window = new CreateOrderChangeWithoutOrderWindow();
                window.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnProcessEx_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FrameworkElement fe = sender as FrameworkElement;
                if (fe == null)
                {
                    MessageBox.Show("事件源不为:FrameworkElement");
                    return;
                }
                OrderChangeViewModel vm = fe.DataContext as OrderChangeViewModel;

                if (vm == null)
                {
                    throw new Exception("DataContext数据为空");
                }

                if (string.IsNullOrWhiteSpace(vm.OrderChange.ReturnDeliveryCompany) || string.IsNullOrWhiteSpace(vm.OrderChange.ReturnDeliveryNumber))
                {
                    throw new Exception("快递公司和快递单号不能为空");
                }

                ReturnProcessWindowEx window = new ReturnProcessWindowEx { OrderChange = vm };
                window.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void btnPrintInfo_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FrameworkElement fe = sender as FrameworkElement;
                if (fe == null)
                {
                    MessageBox.Show("事件源不为:FrameworkElement");
                    return;
                }
                OrderChangeViewModel vm = fe.DataContext as OrderChangeViewModel;

                if ((int)vm.OrderChange.State < (int)OrderChangeState.WaitToVendor)
                {
                    MessageBox.Show("订单没有处理，不能被打印");
                    return;
                }
                PrintDevice.PrintOrderReturn(vm.OrderChange);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void btnPrint_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                OrderChangePrint print = new OrderChangePrint();
                print.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnRefund_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FrameworkElement fe = sender as FrameworkElement;
                if (fe == null)
                {
                    MessageBox.Show("事件源不为:FrameworkElement");
                    return;
                }
                OrderChangeViewModel vm = fe.DataContext as OrderChangeViewModel;
                if (vm == null)
                {
                    throw new Exception("对象数据为空");
                }

                OrderChangeService os = ServiceContainer.GetService<OrderChangeService>();
                os.MarkRefundOk(vm.OrderChange.Id);
                MessageBox.Show("退款成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }


        private void GoodsImage_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FrameworkElement fe = sender as FrameworkElement;
                if (fe == null)
                {
                    return;
                }

                if (fe.Tag == null)
                {
                    return;
                }
                int numberId = (int)fe.Tag;
                if (numberId <= 0)
                {
                    return;
                }
                Shoes s = ServiceContainer.GetService<ShoesService>().GetById(numberId);
                if (s == null)
                {
                    MessageBox.Show("无法获取指定的商品");
                    return;
                }
                if (string.IsNullOrWhiteSpace(s.Url))
                {
                    return;
                }
                Process.Start(s.Url);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnDetail_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FrameworkElement fe = sender as FrameworkElement;
                if (fe == null)
                {
                    MessageBox.Show("事件源不为:FrameworkElement");
                    return;
                }
                OrderChangeViewModel vm = fe.DataContext as OrderChangeViewModel;
                if (vm == null)
                {
                    throw new Exception("对象数据为空");
                }

                OrderReturnDetail de = new OrderReturnDetail { DataContext = vm };
                de.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private static string FormatCSVContent(params string[] values)
        {
            if (values == null || values.Length == 0)
            {
                return "";
            }

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < values.Length; i++)
            {
                sb.Append("\"");
                sb.Append(values[i].Replace("\"", "\"\""));//双引号，需要转义
                sb.Append("\",");
            }
            sb.Length = sb.Length - 1;//支最后一个 , 号
            sb.AppendLine();//增加换行
            return sb.ToString();
        }

        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var orderVm = this.lstOrderChanges.ItemsSource as OrderChangeViewModel[];
                if (orderVm == null || orderVm.Length < 1)
                {
                    MessageBox.Show("没有需要导出的商品");
                    return;
                }

                Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
                sfd.DefaultExt = "csv";
                sfd.AddExtension = true;
                sfd.Filter = "*.csv|CSV文件";
                sfd.FileName = "奇牛退货导出" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + ".csv";
                bool? ret = sfd.ShowDialog();
                if (ret == false || ret.Value == false)
                {
                    return;
                }
                if (File.Exists(sfd.FileName))
                {
                    File.Delete(sfd.FileName);
                }
                VendorService vs = ServiceContainer.GetService<VendorService>();
                //添加头部
                File.AppendAllText(sfd.FileName, FormatCSVContent("退货编号", "订单编号", "卖家编号", "创建时间", "商品信息", "数量", "描述"));
                foreach (var order in orderVm)
                {
                    File.AppendAllText(sfd.FileName, FormatCSVContent(order.OrderChange.Id.ToString(), order.Order == null ? "00000000" : order.Order.Id.ToString(), order.OrderChange.SellerId.ToString(), order.OrderChange.CreateTime.ToString("yyyy-MM-dd"), order.OrderChange.GoodsInfo, order.OrderChange.Count.ToString(), order.OrderChange.SystemComment));
                }
                MessageBox.Show(sfd.FileName, "已成功导出");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnReject_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FrameworkElement fe = sender as FrameworkElement;
                if (fe == null)
                {
                    MessageBox.Show("事件源不为:FrameworkElement");
                    return;
                }
                OrderChangeViewModel vm = fe.DataContext as OrderChangeViewModel;
                if (vm == null)
                {
                    throw new Exception("对象数据为空");
                }
                new OrderChangeRejectWindow { OrderChangeId = vm.OrderChange.Id }.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FrameworkElement fe = sender as FrameworkElement;
                if (fe == null)
                {
                    MessageBox.Show("事件源不为:FrameworkElement");
                    return;
                }
                OrderChangeViewModel vm = fe.DataContext as OrderChangeViewModel;
                if (vm == null)
                {
                    throw new Exception("对象数据为空");
                }

                if (MessageBox.Show("是否删除退货编号：" + vm.OrderChange.Id, "警告", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
                {
                    return;
                }

                if (MessageBox.Show("是否删除退货编号：" + vm.OrderChange.Id, "警告", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
                {
                    return;
                }

                OrderChangeService os = ServiceContainer.GetService<OrderChangeService>();
                os.Delete(vm.OrderChange.Id);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
